import numpy as np
import sklearn.cluster as skc
from sklearn import metrics
import matplotlib.pyplot as plt

mac2id = dict()
onlinetimes = []
# 学生月上网时间分布-TestData
f = open('TestData.txt', encoding='utf-8')
for line in f:
    mac = line.split(',')[2]
    onlinetime = int(line.split(',')[6])
    starttime = int(line.split(',')[4].split(' ')[1].split(':')[0])
    if mac not in mac2id:
        mac2id[mac] = len(onlinetimes)
        onlinetimes.append((starttime, onlinetime))
    else:
        onlinetimes[mac2id[mac]] = [(starttime, onlinetime)]
real_X = np.array(onlinetimes).reshape((-1, 2))

X = real_X[:, 0:1]

# eps 两个样本被看作邻居节点的最大距离
# min_samples 簇的样本数
# metric='euclidean' 距离计算方式
db = skc.DBSCAN(eps=0.01, min_samples=20).fit(X)
# labels 每个数据的簇标签
labels = db.labels_

print('Labels:')
print(labels)
# 计算噪声数据（标签为-1）的比例
raito = len(labels[labels[:] == -1]) / len(labels)
print('Noise raito:', format(raito, '.2%'))

# 计算簇的个数
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)

print('Estimated number of clusters: %d' % n_clusters_)
print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X, labels))

for i in range(n_clusters_):
    # 各簇标号
    print('Cluster ', i, ':')
    # 各簇内数据
    print(list(X[labels == i].flatten()))

# 画直方图
plt.hist(X, 24)
